<?php

namespace App\HttpController\Api;

use App\HttpController\Api\Admin\AdminBase;
use EasySwoole\Component\Di;
use App\Lib\ClassArr;
use EasySwoole\Http\Message\Status;

class Upload extends AdminBase
{

    public function file()
    {
        $request = $this->request();
        $files = $request->getSwooleRequest()->files;
        $types = array_keys($files);
        $type = $types[0];
        if (empty($type)) {
            return $this->toJson(Status::CODE_BAD_REQUEST, [], '上传文件不合法');
        }
        try {
            $classObj = new ClassArr();
            $classStats = $classObj->uploadClassStat();
            $uploadObj = $classObj->initClass($type, $classStats, [$request, $type]);
            $file = $uploadObj->upload();
        } catch(\Exception $e) {
            return $this->toJson(Status::CODE_BAD_REQUEST, [], $e->getMessage());
        }
        if (empty($file['size'])) {
            return $this->toJson(Status::CODE_BAD_REQUEST, [], "上传失败");
        }

        $data = [
            'url' => $file['url'],
            'size'=> $file['size']
        ];
        return $this->toJson(0, $data, 'ok');
    }

}
